package com.nvwa.boot.stater.web.printbeans;

import com.nvwa.coding.util.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class PrintBeansCommandLineRunner implements CommandLineRunner, ApplicationContextAware {
    PrintBeansProperties printBeansProperties;
    ApplicationContext applicationContext;
    public PrintBeansCommandLineRunner(PrintBeansProperties printBeansProperties) {
        this.printBeansProperties = printBeansProperties;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) {
        if (printBeansProperties.isEnabled()) {
            String[] beanNames = applicationContext.getBeanDefinitionNames();
            if (printBeansProperties.isPrintName() && printBeansProperties.isPrintType()) {
                Map<String, String> beanMap = Arrays.stream(beanNames)
                        .collect(Collectors.toMap(k -> k, v -> applicationContext.getBean(v).getClass().getName(), (oldValue, newValue) -> oldValue, TreeMap::new));
                log.info("---spring container bean name&type: {}", JsonUtil.toString(beanMap));
            } else if (printBeansProperties.isPrintName()) {
                List<String> res = Arrays.stream(beanNames).sorted().collect(Collectors.toList());
                log.info("---spring container bean name: {}", JsonUtil.toString(res));
            } else if (printBeansProperties.isPrintType()) {
                List<String> res = Arrays.stream(beanNames)
                        .map(beanName -> applicationContext.getBean(beanName).getClass().getName())
                        .sorted()
                        .collect(Collectors.toList());
                log.info("---spring container bean type: {}", JsonUtil.toString(res));
            }
        }
    }
}
